import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/product_plateconsumption_odoo_api.dart';
import 'package:flutter_admin/api/odoo/product_stockorder_odoo_api.dart';
import 'package:flutter_admin/models/odoo/product_plateconsumption.dart';
import 'package:flutter_admin/models/odoo/product_stockorder.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/product_productunitprice/product_list.dart';
import 'package:multi_select_flutter/bottom_sheet/multi_select_bottom_sheet_field.dart';
import 'package:multi_select_flutter/chip_display/multi_select_chip_display.dart';
import 'package:multi_select_flutter/dialog/multi_select_dialog_field.dart';
import 'package:multi_select_flutter/util/multi_select_item.dart';
import 'package:multi_select_flutter/util/multi_select_list_type.dart';
import '../../../generated/l10n.dart';

class ProductStockorderEdit extends StatefulWidget {
  ProductStockorderEdit({this.productStockorder});

  final ProductStockorder? productStockorder;

  @override
  _ProductStockorderEditState createState() => _ProductStockorderEditState();
}

class _ProductStockorderEditState extends State<ProductStockorderEdit> {
  late ProductStockorder productStockorder;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  List<MultiSelectItem<Object?>> processList = [];

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.productStockorder == null;
    this.productStockorder = widget.productStockorder ?? ProductStockorder();
    // _selectedAnimals5 = _animals;
    _loadSelectVO();
  }

 _loadSelectVO() async{
   ResponseBodyApi responseBodyApi = await DynamicDataApi.getModels(model: "mrp.routing.workcenter");
   if(responseBodyApi.success!){
     for( Map map in responseBodyApi.data){
       processList.add(MultiSelectItem<dynamic>(map["id"], map['name']));
     }
   }
   if(isAdd!){
      var res = await ProductStockorderOdooApi.getOrder();
      if(res.success!){
        productStockorder.stockorderno = res.data;
      }
   }
   setState(() { });
  }

  _selectProduct() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductList(),
      ),
    ).then((v) {
      if (v != null) {
        //_query();
        formKey.currentState!.save();
        productStockorder.productId = v['id'].toString();
        productStockorder.productCode = v['default_code'] != false ? v['default_code'] : '';
        productStockorder.productName = v['name'] != false ? v['name'] : '';
        productStockorder.productDesc = v['description'] != false ? v['description'] : '';
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '备货单号',
            enable: false,
            value: productStockorder.stockorderno,
            onSaved: (v) {
              productStockorder.stockorderno = v;
            },
          ),

           CrySelectDate(
            context,
            label: '备货日期',
            value: productStockorder.orderdate,
            onSaved: (v) {
              productStockorder.orderdate = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInput(
            label: '零件名称',
            value: productStockorder.productName,
            onTap: ()=>{
              _selectProduct()
            },
            onSaved: (v) {
              productStockorder.productName = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInput(
            label: '零件图号',
            enable: false,
            value: productStockorder.productCode,
          ),

          CryInput(
            label: '规格型号',
            enable: false,
            value: productStockorder.productDesc,
          ),

          CryInputNum(
            label: '备货数量',
            value: productStockorder.orderqty,
            onSaved: (v) {
              productStockorder.orderqty = v;
            },
            validator: (v) {
              return double.parse(v!) == 0 ? "备货数量不能为0" : null;
            },
          ),

          Padding(padding: EdgeInsets.all(20),
            child: MultiSelectDialogField(
              items: processList,
              title: Text("工序"),
              listType: MultiSelectListType.LIST,
              searchable: true,
              searchHint: "查找",
              confirmText: Text("确定"),
              cancelText: Text("取消"),
              buttonIcon: Icon(
                Icons.search,
                // color: Colors.blue,
              ),
              buttonText: Text(
                "选择工序",
                style: TextStyle(
                  // color: Colors.blue[800],
                  fontSize: 16,
                ),
              ),
              initialValue: productStockorder.processList,
              onConfirm: (results) {
                productStockorder.processList = results;
              },
              // chipDisplay: MultiSelectChipDisplay(
              //   // chipColor: Colors.black12,
              //   onTap: (value) {
              //     setState(() {
              //       productStockorder.processList!.remove(value);
              //     });
              //   },
              // ), // setting the value of this in initState() to pre-select values.
            ),
          ),

          CryInput(
            label: '备注',
            value: productStockorder.remark,
            onSaved: (v) {
              productStockorder.remark = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            if (productStockorder.processList == null || productStockorder.processList!.length == 0) {
              CryUtils.message("请选择工序");
              return ;
            }
            form.save();
            productStockorder.isSupplement = '0';
            ProductStockorderOdooApi.saveOrUpdate(productStockorder.toOdooMap()).then((ResponseBodyApi res) {
              if (!res.success!) {
               //package:flutter_admin/pages/common/cry(re s.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}